<template>
  <div>
    <el-form :inline="true" :model="tableForm" class="demo-form-inline">
      <el-form-item label="商品名称/id">
        <el-input v-model="tableForm.keyWord" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="订单状态">
        <el-select
          v-model="tableForm.orderStatus"
          placeholder="请选择"
          style="width: 240px"
          clearable
        >
          <el-option label="未支付" value="0" />
          <el-option label="已支付" value="1" />
          <el-option label="待发货" value="2" />
        </el-select>
      </el-form-item>

      <el-form-item label="订单类型">
        <el-select
          v-model="tableForm.orderType"
          placeholder="请选择"
          style="width: 240px"
          clearable
        >
          <el-option label="普通订单" value="0" />
          <el-option label="秒杀订单" value="1" />
          <el-option label="拼团订单" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getList">查询</el-button>
        <el-button type="primary" @click="toSave">添加订单</el-button>
        <el-button type="danger" @click="delBatch">批量删除</el-button>
      </el-form-item>
    </el-form>
  </div>
  <el-table
    :data="tableData"
    :border="true"
    style="width: 100%"
    @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" width="55" />
    <el-table-column prop="orderId" label="订单id" />
    <el-table-column prop="orderNo" label="订单编号" />
    <el-table-column prop="userName" label="下单用户" />
    <el-table-column prop="prodInfo" label="订单信息" />
    <el-table-column prop="orderAmount" label="订单金额" />
    <el-table-column prop="orderStatus" label="订单状态">
      <template #default="scope">
        <el-tag type="warning" v-if="scope.row.orderStatus == 0">未支付</el-tag>
        <el-tag type="success" v-if="scope.row.orderStatus == 1">已支付</el-tag>
        <el-tag type="primary" v-if="scope.row.orderStatus == 2">待发货</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="orderType" label="订单类型">
      <template #default="scope">
        <el-tag type="info" v-if="scope.row.orderType == 0">普通订单</el-tag>
        <el-tag type="danger" v-if="scope.row.orderType == 1">秒杀订单</el-tag>
        <el-tag type="primary" v-if="scope.row.orderType == 2">拼团订单</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="prodImagesList" label="商品图片">
      <template #default="scope">
        <el-image
          style="width: 100px; height: 100px"
          v-for="value in scope.row.prodImagesList"
          :src="value"
        />
      </template>
    </el-table-column>
    <el-table-column prop="createTime" label="创建时间" />
    <el-table-column label="操作">
      <template #default="scope">
        <el-button type="primary" @click="toExport(scope.row)"
          >导出订单</el-button
        >
      </template>
    </el-table-column>
  </el-table>
  <div class="demo-pagination-block">
    <el-pagination
      v-model:current-page="tableForm.pageNum"
      v-model:page-size="tableForm.pageSize"
      :page-sizes="[3, 6, 9, 12]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
  <el-dialog v-model="dialogFormVisible" title="填写信息" width="700">
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="saveForm"
      :rules="rules"
      label-width="auto"
    >
      <el-form-item label="选择商品" prop="prodId">
        <el-select
          v-model="saveForm.prodId"
          placeholder="请选择"
          style="width: 240px"
          clearable
        >
          <el-option
            v-for="value in upProdSelect"
            :label="value.prodName"
            :value="value.prodId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="购买数量" prop="buyNum">
        <el-input-number v-model="saveForm.buyNum" :min="1" />
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="saveBelow"> 添加商品 </el-button>
    <el-table :data="infoData" :border="true" style="width: 100%">
      <el-table-column prop="prodName" label="商品名称" />
      <el-table-column prop="prodPrice" label="商品价格" />
      <el-table-column prop="buyNum" label="商品数量" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" @click="delAmong(scope.row)">
            移除商品
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="font-size: large; color: brown">
      商品总价格：{{ totalPrice }}
    </div>
    <el-form-item>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        确定
      </el-button>
    </el-form-item>
  </el-dialog>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import {
  SelectOrderList,
  selectUpGoods,
  saveOrderOk,
  delBatchOrder,
} from "../api/api";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
const ruleFormRef = ref<FormInstance>();
const dialogFormVisible = ref(false);
const tableForm = ref({
  endTime: "",
  keyWord: "",
  orderStatus: null,
  orderType: null,
  pageNum: 1,
  pageSize: 2,
  startTime: "",
});
const multipleSelection = ref([]);
const saveForm = ref({});

const toExport = () => {
  let url = "http://localhost:9002/shop/index/exportOrder";
  window.open(url);
};

const toSave = () => {
  dialogFormVisible.value = true;
  console.log("list", upProdSelect);
};

const rules = ref({
  prodId: [{ required: true, message: "请选择商品", trigger: "blur" }],
  buyNum: [{ required: true, message: "请输入数量", trigger: "blur" }],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      // 调用保存接口
      saveOrderOk(infoData.value).then((res) => {
        if (res.data.flag) {
          ElMessage.success("保存成功");
          dialogFormVisible.value = false;
          getList();
          reset();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
const infoData = ref([]);
const tableData = ref([]);
const total = ref(0);
const totalPrice = ref(0);
const getList = () => {
  SelectOrderList(tableForm.value).then((res) => {
    tableData.value = res.data.data.records;
    total.value = res.data.data.total;
  });
};

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  getList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  getList();
};

const delBatch = () => {
  if (multipleSelection.value.length <= 0) {
    ElMessage.warning("请先选择数据！！");
    return;
  }
  let ids = [];
  multipleSelection.value.forEach((item) => {
    ids.push(item.orderId);
  });
  ElMessageBox.confirm("删除后数据不可恢复，确定要删除吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "警告",
  })
    .then(() => {
      delBatchOrder(ids).then((res) => {
        if (res.data.flag) {
          ElMessage.success("成功删除" + ids.length + "条数据");
          getList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消操作",
      });
    });
};

const saveBelow = () => {
  let prodInfo = {
    prodId: null,
    infoId: null,
    buyNum: null,
    prodPrice: null,
    prodName: "",
  };

  if (saveForm.value.prodId == null) {
    ElMessage.error("请先选择购买的商品");
    return;
  }
  if (saveForm.value.buyNum == null) {
    ElMessage.error("请输入购买数量");
    return;
  }

  upProdSelect.value.forEach((item) => {
    let flag = false;
    if (item.prodId == saveForm.value.prodId) {
      prodInfo.infoId = item.infoId;
      prodInfo.prodId = item.prodId;
      prodInfo.buyNum = saveForm.value.buyNum;
      prodInfo.prodPrice = saveForm.value.buyNum * item.prodPrice;
      prodInfo.prodName = item.prodName;
      totalPrice.value = totalPrice.value + prodInfo.prodPrice;
      // 是否加入购物车
      infoData.value.forEach((item) => {
        if (item.prodId == prodInfo.prodId) {
          item.buyNum = item.buyNum + saveForm.value.buyNum;
          item.prodPrice = item.prodPrice + prodInfo.prodPrice;
          flag = true;
          return;
        }
      });
      if (!flag) {
        infoData.value.push(prodInfo);
      }
      return;
    }
  });
};
const delAmong = (row: any) => {
  infoData.value.forEach((item: any, index: any) => {
    if (item.prodId == row.prodId) {
      infoData.value.splice(index, 1);
      totalPrice.value = totalPrice.value - item.prodPrice;
    }
  });
};

const reset = () => {
  saveForm.value = {
    prodId: null,
    buyNum: null,
  };
  totalPrice.value = 0;
  infoData.value = [];
};
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val;
};

const upProdSelect = ref([]);
// 页面加载钩子函数
onMounted(() => {
  getList();

  selectUpGoods().then((res) => {
    upProdSelect.value = res.data.data;
  });
});
</script>
